package cn.net.ecode.elec.api.web;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.elec.caculate.entity.ElecEarningsCalculate;
import cn.net.ecode.elec.caculate.service.ElecEarningsCalculateService;
import cn.net.ecode.elec.template.entity.ElecTemplate;
import cn.net.ecode.elec.template.service.ElecTemplateService;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @ClassName AppEarningsController
 * @Description 收益计算相关接口
 * @Author AlanShelby
 * @Date 2019-09-04 14:24:14 14:24
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/earnings")
public class AppEarningsController extends BaseController {

    @Autowired
    private ElecTemplateService templateService;

    @Autowired
    private ElecEarningsCalculateService elecEarningsCalculateService;

    /**
     * @Method economizeSum
     * @Description 度电节省金额
     * @Author AlanShelby
     * @Date 14:30 2019/9/4 0004
     * @Param [templateKey]
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping("/economizeSum")
    public R economizeSum(@RequestParam String templateKey) {
        ElecTemplate template = templateService.getByTemplateKey(templateKey);
        if (template == null) {
            R.error("度电节省金额异常，请联系管理员");
        }

        return R.ok().put("economizeSum", template.getTemplateValue());
    }

    /**
     * @Method caculate
     * @Description 收益测算
     * @Author AlanShelby
     * @Date 9:14 2019/9/6 0006
     * @Param [elecEarningsCalculate]
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping(value = "/caculate", method = RequestMethod.POST)
    public R caculate(@RequestBody ElecEarningsCalculate elecEarningsCalculate) {
        StringBuilder message = new StringBuilder();
        if (!beanValidator(message, elecEarningsCalculate)) {
            return R.error(message.toString());
        }

        // 节省金额
        // 获取度电节省金额
        ElecTemplate template = templateService.getByTemplateKey("economize_sum");
        String economizeSumStr = template.getTemplateValue();
        DecimalFormat format = new DecimalFormat("#.00");
        BigDecimal economizeSum = new BigDecimal(economizeSumStr);
        BigDecimal yearElectric = new BigDecimal(elecEarningsCalculate.getYearElectric());
        String result = format.format(yearElectric.multiply(economizeSum));

        // 插入数据
        elecEarningsCalculate.preInsert();
        elecEarningsCalculate.setCreateBy(new User(elecEarningsCalculate.getPhone()));
        elecEarningsCalculate.setUpdateBy(new User(elecEarningsCalculate.getPhone()));
        elecEarningsCalculateService.insert(elecEarningsCalculate);

        return R.ok().put("result", result);
    }
}
